﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace SmartMathLibrary.IO
{
    /// <summary>
    /// This class provides methods to write one or more matrices to a xml file.
    /// </summary>
    [Serializable]
    public class MatrixFileWriter : AbstractXmlFileWriter
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MatrixFileWriter"/> class.
        /// </summary>
        /// <param name="stream">The stream of the file writer.</param>
        /// <param name="encoding">The encoding of the file.</param>
        public MatrixFileWriter(Stream stream, Encoding encoding)
            : base(stream, encoding)
        {
            this.writeEngine.WriteStartElement("Matrices");
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="MatrixFileWriter"/> class.
        /// </summary>
        /// <param name="filename">The filename.</param>
        /// <param name="encoding">The encoding.</param>
        public MatrixFileWriter(String filename, Encoding encoding)
            : base(filename, encoding)
        {
            this.writeEngine.WriteStartElement("Matrices");
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="MatrixFileWriter"/> class.
        /// </summary>
        /// <param name="textWriter">The text writer.</param>
        public MatrixFileWriter(TextWriter textWriter)
            : base(textWriter)
        {
            this.writeEngine.WriteStartElement("Matrices");
        }

        /// <summary>
        /// Writes the specified matrix to the specified file.
        /// </summary>
        /// <param name="matrix">The matrix to write.</param>
        public void Write(Matrix matrix)
        {
            this.writeEngine.WriteStartElement("Matrix");

            for (int rows = 0; rows < matrix.Rows; rows++)
            {
                this.writeEngine.WriteStartElement("Row");

                for (int columns = 0; columns < matrix.Columns; columns++)
                {
                    this.writeEngine.WriteElementString("Column", matrix.GetValueAtPosition
                                                                      (new MatrixPosition(rows, columns)).ToString());
                }

                this.writeEngine.WriteEndElement();
            }

            this.writeEngine.WriteEndElement();
        }

        /// <summary>
        /// Closes the writer and saves the output values.
        /// </summary>
        public override void Close()
        {
            this.writeEngine.WriteEndElement();
            base.Close();
        }
    }
}